package com.gta.edu.sdk.config.redis;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gta.edu.sdk.config.datasource.DBDecode;

@Aspect
@Configuration
@ConfigurationProperties(prefix="spring.redis")
public class RedisConfig {
	
	@Autowired
	private RedisProperties redisProperties;
	@Value("${spring.redis.password}")
	private String password;
	
	@Before("com.gta.edu.sdk.config.redis.RedisPointCut.getReidsConnectionPwd()")
	public void setRedisPassword() {
		String psw = DBDecode.decryptDecode(password);
		redisProperties.setPassword(psw);
	}
	
	@Bean
	public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory factory){
		RedisTemplate<Object,Object> template = new RedisTemplate();
		template.setConnectionFactory(factory);
		// 对对象进行序列化，替代默认方式
		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
		
		// 设置value和KEY的序列化规则
		template.setKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(jackson2JsonRedisSerializer);
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setHashValueSerializer(jackson2JsonRedisSerializer);
		template.afterPropertiesSet();
		
		return template;
	}
}
